package com.jiagoushi.cloud.study.user.controller;

import com.jiagoushi.cloud.study.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@RestController
public class OrderController {

	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private RestTemplate restTemplate;

	@HystrixCommand(fallbackMethod = "findByIdFallback",
					groupKey = "orderUserGroup",
					threadPoolKey = "orderUserIdThreadPool",
					threadPoolProperties = {
	        			@HystrixProperty(name = "coreSize", value = "2"),  //线程池大小2个，
	        			@HystrixProperty(name = "maxQueueSize", value = "3"),
	        			@HystrixProperty(name = "queueSizeRejectionThreshold", value = "1") })  //队列长度1，其他线程被降级处理， //maxQueueSize和queueSizeRejectionThreshold 简单理解两者取最小值做为队列长度
	@GetMapping("/user/{id}")
	public User findById(@PathVariable Long id) {
		logger.info("================请求用户中心接口，用户id:" + id + "==============");
		return restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
	}

	@HystrixCommand(fallbackMethod = "findByIdFallback",
			groupKey = "orderUserGroup",
			threadPoolKey = "orderUserIdThreadPool",
			threadPoolProperties = {
					@HystrixProperty(name = "coreSize", value = "2"), //配置线程池线程数量
					@HystrixProperty(name = "maxQueueSize", value = "2"),
					@HystrixProperty(name = "queueSizeRejectionThreshold", value = "1") })
	@GetMapping("/user/name/{userName}")
	public User findByUserName(@PathVariable String userName) {
		logger.info("================请求用户中心接口，用户userName:" + userName + "==============");
		return restTemplate.getForObject("http://microservice-provider-user/" + userName, User.class);
	}

	//降级方法
	public User findByIdFallback(Long id) {
		User user = new User();
		user.setId(-1L);
		user.setName("降级用户");
		return user;
	}
	
}
